#!/bin/bash -e

#
# This script is indented to be used in automatic cronjobs for
# scanning the linux git tree for dead blocks and do coverage analysis
# on it.
#

giturl="git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git"

function usage() {
    echo "usage: ${0##*/} <-d DIR> [-c REV] [-t PROCS]"
    echo " -d   directory the linux tree will be cloned to"
    echo " -t   undertaker processes to be run"
    echo "      default: _NPROCESSORS_ONLN"
    echo " -c   commit to be used"
    echo "      default: HEAD"
    exit 2
}

while getopts ":d:t:c:" OPT; do
    case $OPT in
        d)
            GIT_DIRECTORY="$OPTARG"
            ;;
        t)
            PROCESSORS="$OPTARG"
            ;;
        c)
            COMMIT="$OPTARG"
            ;;
        *)
           usage
           ;;
    esac
done
shift $(( OPTIND - 1 ))
OPTIND=1

PROCESSORS=${PROCESSORS:-$(getconf _NPROCESSORS_ONLN)}
COMMIT=${COMMIT:-HEAD}

if [ -z "$GIT_DIRECTORY" ]; then
    echo "Error: No directory for the linux tree was given."
    echo 
    usage
fi

if ! which  undertaker-kconfigdump > /dev/null; then
    echo "No undertaker-kconfigdump executable found."
    exit 1
fi

if ! which  undertaker-linux-tree > /dev/null; then
    echo "No undertaker-linux-tree executable found."
    exit 1
fi


if [ ! -d "$GIT_DIRECTORY" ]; then
    git clone "$giturl" "$GIT_DIRECTORY"
fi

resultdir="$GIT_DIRECTORY"/results
cd "$GIT_DIRECTORY"
mkdir -p "$resultdir"

echo "Running on Linux Version $(git describe || echo '(no git)')"
git clean -fxq
git reset --hard
git pull

version="$(git describe || date +%Y-%m-%d-%H:%M)"
report="${resultdir}/${version}-report.txt"
deadlist="${resultdir}/${version}-deads.txt"

echo "Scanning version ${version}, logging to ${report}"

undertaker-kconfigdump  > "$report" 2> dump-rsf-error-output.txt

undertaker-linux-tree -t ${PROCESSORS}    >>"$report" 2>undertaker-error-output.txt
find . -name '*dead' -ls > "$deadlist"
echo "Found $(grep globally $deadlist | wc -l) globally dead blocks"


undertaker-linux-tree -t ${PROCESSORS} -c >>"$report" 2>coverage-error-output.txt
echo "TOP 15 variable implementation files (format: #possible solutions, filename)"
grep '.c$' "${report}"




